package org.brownflat.lighthouse.monitoring.ci.teamcity;

import org.brownflat.lighthouse.cache.HistoryService;
import org.brownflat.lighthouse.monitoring.ci.Builder;
import org.brownflat.lighthouse.monitoring.ci.ConnectionException;
import org.brownflat.lighthouse.monitoring.ci.Feed;
import org.brownflat.lighthouse.monitoring.ci.HTTPServer;
import org.brownflat.lighthouse.monitoring.ci.Monitorable;
import org.brownflat.lighthouse.util.Profiled;

public class TeamCityServer extends HTTPServer implements Monitorable {

    private Builder<Feed, String> builder;

    private HistoryService historyService = new HistoryService.DoNothingHistoryService();

    private Feed feed;

    public TeamCityServer() {
        super("localhost", 8080);
    }


    public TeamCityServer(String host, int port, Builder<Feed, String> builder) {
        super(host, port);
        this.builder = builder;
    }

    public TeamCityServer(String host, int port, String path, Builder<Feed, String> builder) {
        super(host, port, path);
        this.builder = builder;
    }

    @Override
    @Profiled
    public void run() {
        try {
            String result = execute(new TeamCityLatestBuildsRequest());
            feed = builder.build(result);
            historyService.record(feed);
        } catch (ConnectionException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean isBroken() {
        return feed != null && feed.isCurrentlyBroken();
    }

    @Override
    public Feed getLatestFeed() {
        return feed;
    }

    @Override
    public String getLocation() {
        return getUrl();
    }

    @Override
    public String getName() {
        return "TeamCity";
    }

    public void setHistoryService(HistoryService historyService) {
        this.historyService = historyService;
    }
}
